package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.ParseException
import java.text.SimpleDateFormat;
import java.time.Instant

import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import cn.com.kh.hst.ThreeDesUtil
import cn.com.kh.KHUtil;
import cn.com.kh.getProperty;


/**
 *
 * @Title: aipHSTsubBankCardList
 * @Description:华盛证券 银行子账号列表查询 --内部接口
 * @author: chieh
 * @date 2022-11-10 14:46:00
 *
 */

public class aipHSTsubBankCardList implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTsubBankCardList.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String inData = "";
        String outData = "";
        String totalData = "";
        String dataSourceID = "dataSource";


        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        inData = URLDecoder.decode(inData, "UTF-8");
        log.debug("原始inData URLDecoder:" + inData);

        try {

            long startTime = System.currentTimeMillis();
            String reJson = null;
            long endTime = 0;
            JSONObject inObject = new JSONObject(inData);
            //鉴权变量
            String appid = getProperty.get("appid");
            String appsecret = getProperty.get("appsecret");

            //sign加密前后
            String signfront = "";
            String signafter = "";
            def token = GetJV(inObject, "token");

            String sign_time=Instant.now().getEpochSecond();
            log.debug("解析信息-" +  "sign_time: " + sign_time);

            HashMap<String, String> paramHashMap = new HashMap<String, String>() {
                {
                    //put("token", token);
                    put("sign_time", sign_time);
                }
            };

            log.debug("paramHashMap：" + paramHashMap);
            //自然排序 升序参数
            signfront= ThreeDesUtil.sortMap(paramHashMap,appid,appsecret);
            log.debug("sign加密MD5前：" + signfront);
            signafter = Util.getMD5Str(signfront);
            log.debug("sign加密MD5后：" + signafter);

            //拼接接口入参
            paramHashMap.put("client_key", appid);
            paramHashMap.put("sign", signafter);

            String injson=ThreeDesUtil.SplicingMap(paramHashMap,"&");
            log.debug("injson:" + injson);

            String[] GDSQL = new String[3];
            GDSQL[0] = "DELETE FROM hst_subBankCardList_his where synchroDate<= DATE_SUB(CURDATE(), INTERVAL 30 DAY)  ";
            GDSQL[1] = "Insert into hst_subBankCardList_his select * from hst_subBankCardList where synchroDate<str_to_date(DATE_FORMAT(NOW(),'%Y-%m-%d'),'%Y-%m-%d %H:%i:%s')";
            GDSQL[2] = "delete from hst_subBankCardList where synchroDate<str_to_date(DATE_FORMAT(NOW(),'%Y-%m-%d'),'%Y-%m-%d %H:%i:%s')";
            def GDresult = eliteBean.updateBatch(GDSQL, "dataSource");

            outData = Querypromocode(eliteBean, injson,dataSourceID);

            //outData = "{\"result\":\"1\",\"message\":\"处理成功\",\"data\":[]}";

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"result\":\"-1\",\"message\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        return outData;
    }

    //调度华盛接口--银行子账号列表接口
    public static String Querypromocode(EliteBean eliteBean , String injson, String dataSourceID) {

        long startTime = System.currentTimeMillis();
        log.debug("处理开始时间:" + startTime);

        long endTime = System.currentTimeMillis();

        String reJson = null;
        try {

            String doURL = getProperty.get("HSTURL");
            doURL = doURL+"/crm/money/sub-bank-list";
            log.debug("doURL:" + doURL);
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/x-www-form-urlencoded");
            def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
            log.debug("getResult:" + getResult);
            //UUID uuid = UUID.randomUUID();

            //解析返回信息
            JSONObject jsonObject = new JSONObject(getResult);
            String code = GetJV(jsonObject, "code");
            String result = GetJV(jsonObject, "result");

            log.debug("code:" + code);
            if(code == "00000") {

                SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = dateformat.format(System.currentTimeMillis());

                JSONArray arrJsonArray = new JSONArray(result);
                int arrInt = arrJsonArray.length();

                //初始化，全部更新为未启用
                def initialupdateresult = eliteBean.update(
                        "UPDATE c_codetables SET  Use_Status = '0', Modifiedby ='SELITE' , Modifieddate = now() WHERE Use_Type = '银行子账号列表'", "dataSource");

                for (int i = 0; i < arrInt; i++) {
                    JSONObject arrSmsJson = arrJsonArray.getJSONObject(i);
                    String bankCardId =GetJV(arrSmsJson,"bankCardId");//主账号ID
                    String bankCode=GetJV(arrSmsJson,"bankCode");//银行编码
                    String bankDesc=GetJV(arrSmsJson,"bankDesc");//银行名称
                    //ALL：所有  CNY：人民币  HKD：港币  USD：美元  NZD：新西兰元
                    String currencyCode=GetJV(arrSmsJson,"currencyCode");//支持的币种

                    log.debug("bankCardId:	" +bankCardId + "bankCode:	" +bankCode + "bankDesc:	" +bankDesc + "currencyCode:	" +currencyCode);

                    String use_states;
                    //渣打银行 港币 美元 手动注释
                    if(bankCode=="SCB"){
                        use_states="0"
                    }else if(bankCode=="CITI"&&currencyCode=="USD"){//花旗银行香港分行 美元 手动注释
                        use_states="0"
                    }else{
                        use_states="1";
                    }
                    log.debug("use_states:	"+use_states);
                    
                    def dataresult = eliteBean.update(
                            "insert into hst_subBankCardList (bankCardId, bankCode, bankDesc, currencyCode, synchroDate) VALUES ('"+bankCardId+"','"+bankCode+"','"+bankDesc+"','"+currencyCode+"',now())", "dataSource");
                    def selectresult=eliteBean.chaxun_sql("select Code_id from c_codetables where code_id='"+bankCardId+"' and Use_Type='银行子账号列表'","dataSource");
                    if(selectresult.size()>0) {
                        def updateresult = eliteBean.update(
                                "UPDATE c_codetables SET  bankCode = '"+bankCode+"',bankDesc = '"+bankDesc+"',currencyCode = '"+currencyCode+"', Use_Status = '"+use_states+"', Modifiedby ='SELITE' , Modifieddate = now() WHERE Code_id = '"+bankCardId+"' and  Use_Type = '银行子账号列表'", "dataSource");
                    }else {
                        def insertresult = eliteBean.update(
                                "INSERT INTO c_codetables (Code_Guid, Code_ID, bankCode, bankDesc,currencyCode, Use_Type, Use_Status, Createdby, Createddate, Modifiedby, Modifieddate) VALUES (UUID(),'"+bankCardId+"','"+bankCode+"','"+bankDesc+"','"+currencyCode+"','银行子账号列表','"+use_states+"','SELITE',now(),'SELITE',now())", "dataSource");
                    }

                }
                reJson = "{\"result\":\"1\",\"message\":\"子账户列表数据同步成功\"}";

            }else {
                String msg = GetJV(jsonObject, "msg");
                reJson = "{\"result\":\"-1\",\"message\":\"用户获取失败(" + msg + ")\"}";
            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            reJson = "{\"result\":\"-1\",\"message\":\"接口异常\"}";
        }
        return reJson;
    }


    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }


    // 非空校验isNull
    public static boolean isNull(String value) {

        boolean reFlag = true;
        if (value == "" || value.length() <= 0) {
            reFlag = true;
        } else {
            reFlag = false;
        }
        log.debug(reFlag);
        return reFlag;
    }

    // 非空校验isNullMSG
    public static String isNullMSG(String key, String value) {

        String reResult = "";
        if (value == "" || value.length() <= 0) {
            reResult = key + "必填字段;";
        }
        return reResult;
    }

}
